package com.yugao.fintech.antelope.system.listener;

import com.rabbitmq.client.Channel;
import com.yugao.fintech.antelope.base.datasource.CommonService;
import com.yugao.fintech.antelope.base.model.constants.TenantCons;
import com.yugao.fintech.antelope.system.model.mq.TenantDeleteMQ;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.util.Objects;

@Slf4j
@Component
@RabbitListener(bindings = {
        @QueueBinding(
                value = @Queue(value = TenantDeleteMQ.QUEUE, durable = "true"),
                exchange = @Exchange(value = TenantDeleteMQ.EXCHANGE, type = ExchangeTypes.FANOUT))
})
public class TenantDeleteListener {

    @Autowired
    private CommonService commonService;

    @RabbitHandler
    public void onMessage(@Payload String msg, Channel channel, Message message) {
        TenantDeleteMQ.MsgPayload tenantDelete = TenantDeleteMQ.parse(msg, TenantDeleteMQ.MsgPayload.class);
        if (Objects.isNull(tenantDelete.getTenantId())) {
            return;
        }
        if (TenantCons.SYSTEM_TENANT_ID.compareTo(tenantDelete.getTenantId()) == 0) {
            return;
        }
        commonService.deleteAllDataByTenantId(tenantDelete.getTenantId());
    }
}
